package com.solotiger.douban.factory;


import com.solotiger.douban.common.GlobalContants;

import java.io.File;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;

/**
 * 初始化OkHttpClient并对外提供该实例的单例
 */

public enum OKHttpFactory {
    INSTANCE;

    private final OkHttpClient okHttpClient;

    private static final int TIMEOUT_READ = 15000;
    private static final int TIMEOUT_CONNECTION = 15;

    OKHttpFactory() {
        //打印请求Log
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        okHttpClient = new OkHttpClient.Builder()
                //打印请求log
                .addInterceptor(interceptor)
                //失败重连
                .retryOnConnectionFailure(true)
                //time out
                .readTimeout(TIMEOUT_READ, TimeUnit.SECONDS)
                .connectTimeout(TIMEOUT_CONNECTION, TimeUnit.SECONDS)
                .cache(new Cache(new File(GlobalContants.GLOBAL_CACHE_PATH), 1024 * 1024 * 300))
                .build();
    }

    public OkHttpClient getOkHttpClient() {
        return okHttpClient;
    }
}
